<?php

namespace addons\yunfood\model;

use addons\yunfood\library\Logic;
use addons\yunfood\library\ModelTrait;
use think\Model;
use traits\model\SoftDelete;

/**
 * 参数模型
 */
class FoodParam extends Model
{
    use ModelTrait;
    use SoftDelete;

    // 表名,不含前缀
    protected $name = 'yunfood_food_param';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $deleteTime = 'deleted_at';
    protected $updateTime = 'updated_at';
    protected $createTime = 'created_at';

    // 不显示的字段
    protected $hidden = ['deleted_at'];

    protected $resultSetType = 'collection';

    // 门店名称
    public function getShopTextAttr($value, $data)
    {
        return Logic::getShopNames($data['shop_ids']);
    }

    // 类型
    const TYPE_SPEC  = 'spec';
    const TYPE_ATTR  = 'attr';
    const TYPE_NOTE  = 'note';
    const TYPE_ADDON = 'addon';

    public static function getTypeList()
    {
        return [
            self::TYPE_SPEC  => __('规格'),
            self::TYPE_ATTR  => __('属性'),
            self::TYPE_NOTE  => __('备注'),
            self::TYPE_ADDON => __('菜品')
        ];
    }

    public function getTypeTextAttr($value, $data)
    {
        $optionList = self::getTypeList();

        return $optionList[$data['type']] ?? $data['type'];
    }

    public function getItemsTextAttr($value, $data)
    {
        if ($data['type'] === self::TYPE_ADDON) {
            $names = [];
            if ($data['items']) {
                $foodList = Food::where('id', 'in', explode(',', $data['items']))->select()->toArray();
                if ($foodList) {
                    $names = array_column($foodList, 'name');
                }
            }

            return implode(',', $names);
        }

        return $data['items'];
    }
}
